package com.example.daily.ui.foodrecognition

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.selection.selectable
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.example.daily.ui.navigation.Screen

@Composable
fun FoodRecognitionScreen(
    viewModel: FoodRecognitionViewModel = hiltViewModel(),
    navController: NavController,
    onSaveResult: (String, Int) -> Unit = { _, _ -> }
) {
    val uiState by viewModel.uiState.collectAsState()
    var selectedResult by remember { mutableStateOf<RecognitionResult?>(null) }

    // 处理相机返回的照片
    LaunchedEffect(navController) {
        val savedStateHandle = navController.currentBackStackEntry?.savedStateHandle
        val photoUri = savedStateHandle?.get<String>("photo_uri")
        if (photoUri != null) {
            viewModel.setSelectedImage(Uri.parse(photoUri))
            savedStateHandle.remove<String>("photo_uri")
        }
    }

    val imagePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let { viewModel.setSelectedImage(it) }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 图片选择按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
        Button(
            onClick = { imagePickerLauncher.launch("image/*") },
                modifier = Modifier.weight(1f).padding(end = 8.dp)
            ) {
                Text("从相册选择")
            }
            
            Button(
                onClick = { navController.navigate(Screen.Camera.route) },
                modifier = Modifier.weight(1f).padding(start = 8.dp)
        ) {
                Text("拍照")
        }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 显示选中的图片
        uiState.selectedImageUri?.let { uri ->
            AsyncImage(
                model = uri,
                contentDescription = "选中的食物图片",
                modifier = Modifier
                    .fillMaxWidth()
                    .height(200.dp),
                contentScale = ContentScale.Crop
            )
        }

        // 加载状态
        if (uiState.isLoading) {
            CircularProgressIndicator(
                modifier = Modifier.padding(16.dp)
            )
        }

        // 错误信息
        uiState.error?.let { error ->
            Text(
                text = error,
                color = MaterialTheme.colorScheme.error,
                modifier = Modifier.padding(16.dp)
            )
        }

        // 识别结果列表
        LazyColumn(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
        ) {
            items(uiState.recognitionResults) { result ->
                ListItem(
                    headlineContent = { Text(result.label) },
                    supportingContent = { Text("置信度: ${(result.confidence * 100).toInt()}% | 卡路里: ${result.calories}") },
                    modifier = Modifier
                        .selectable(
                            selected = selectedResult == result,
                            onClick = { selectedResult = result }
                        )
                        .fillMaxWidth(),
                    colors = ListItemDefaults.colors(
                        containerColor = if (selectedResult == result) {
                            MaterialTheme.colorScheme.primaryContainer
                        } else {
                            MaterialTheme.colorScheme.surface
                        }
                    )
                )
            }
        }

        // 保存按钮
        Button(
            onClick = {
                selectedResult?.let {
                    navController.previousBackStackEntry?.savedStateHandle?.set("food_name", it.label)
                    navController.previousBackStackEntry?.savedStateHandle?.set("food_calories", it.calories)
                    navController.popBackStack()
                }
            },
            enabled = selectedResult != null,
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 16.dp)
        ) {
            Text("保存选中的食物")
        }
    }
} 